/**
 * 
 */
package masterlink.futures.controller;

import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.GregorianCalendar;

import javax.servlet.http.HttpServletRequest;

import masterlink.futures.dao.EquityHisDao;
import masterlink.futures.util.WebUtils;
import masterlink.futures.vo.Account;
import masterlink.futures.vo.Employee;
import masterlink.futures.vo.Group;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;

/**
 * @author tonyyang
 *
 */
@Controller
@RequestMapping(value = "/equityHis")
public class EquityHisController extends BasicController{
	
	private static final SimpleDateFormat df=new SimpleDateFormat("yyyyMMdd"); 
	@Autowired
	private EquityHisDao dao;
	
	@RequestMapping(method=RequestMethod.GET)
	@Override
	public String index(HttpServletRequest req){
		return setData(getStart(), getEnd(), req);
	}
	
	@RequestMapping(method=RequestMethod.POST)
	public String index(@RequestParam("start")String start,@RequestParam("end")String end,HttpServletRequest req) throws Exception{
		return setData(start, end, req);
	}
	
	private String setData(String start, String end, HttpServletRequest req){
		Employee emp=WebUtils.getLogEmployee(req);
		Group g=WebUtils.getGroup(req);
		Account acno=WebUtils.getAccount(req);
		req.setAttribute("START",start);
		req.setAttribute("END",end);
		if(acno!=null){
			log.trace(emp+" in /equityHis loading time : {} ~ {} acno : "+acno,start,end);
			req.setAttribute("EquityHis", dao.findByAccount(g,acno, getTime(start), getTime(end)));
			return "data/aEquityHis";
		}else{
			log.trace(emp+" in /equityHis loading time : {} ~ {} group : "+g,start,end);
			req.setAttribute("EquityHis", dao.findByGroup(g, getTime(start), getTime(end)));
			return "data/rEquityHis";
		}
	}
	
	private String getStart(){
		Calendar cal=new GregorianCalendar();
		cal.set(Calendar.DAY_OF_MONTH, cal.getMinimum(Calendar.DAY_OF_MONTH));
		return df.format(cal.getTime());
	}
	
	private String getEnd(){
		Calendar cal=new GregorianCalendar();
		cal.set(Calendar.DAY_OF_MONTH, cal.getMaximum(Calendar.DAY_OF_MONTH));
		return df.format(cal.getTime());
	}
	
	
	private Long getTime(String time){
		return Long.valueOf((time));
	}
	
}
